package com.tiger.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class Jwt {
    @Value("${JwtPrivateKey}")
    private String JwtPrivateKey;

    @Value("${JwtExpire}")
    private long JwtExpire;

    public long getJwtExpire() {
        return JwtExpire;
    }

    public String createToken(Map<String, ?> data) {
        // 过期时间,7天
        Date expireDate = new Date(System.currentTimeMillis() + JwtExpire * 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = JWT.create()
                // 添加头
                .withHeader(map)
                // 可以将基本信息放到 claims 中
                .withClaim("data", data)
                // 签发时间
                .withIssuedAt(new Date())
                .withExpiresAt(expireDate)
                // SECRET 加密
                .sign(Algorithm.HMAC256(JwtPrivateKey));


        return token;
    }

    /**
     * 校验 token 并解析 token
     * @param token token
     * @return token 中的 claims
     */
    public Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(JwtPrivateKey)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println("token 解码异常");
            // 解码异常则抛出异常
            return null;
        }
        return jwt.getClaims();
    }
}